package root.electronclass.electronclass

import android.Manifest
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.net.ConnectivityManager
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.TextView
import androidx.activity.viewModels
import androidx.appcompat.app.ActionBar
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.lifecycle.coroutineScope
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.SPUtils
import com.hikvision.dmb.system.InfoSystemApi
import com.hikvision.dmb.util.InfoUtilApi
import com.hikvision.smarteyes.smartdev.FaceSdk
import com.jackwang.updateapk.UpdateApp
import com.jackwang.updateapk.UpdateListener
import com.tencent.upgrade.core.DefaultUpgradeStrategyRequestCallback
import com.tencent.upgrade.core.UpgradeManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import retrofit2.Call
import retrofit2.Response
import root.electronclass.electronclass.adapter.FragmentTabAdapter
import root.electronclass.electronclass.adapter.FragmentTabAdapter.OnRgsExtraCheckedChangedListener
import root.electronclass.electronclass.application.ApplicationFragment
import root.electronclass.electronclass.common.base.CommonDialogFragment
import root.electronclass.electronclass.common.base.ViewBindingActivity
import root.electronclass.electronclass.common.event.NetWorkEvent
import root.electronclass.electronclass.common.event.PersonSuccess
import root.electronclass.electronclass.common.util.DeviceType
import root.electronclass.electronclass.common.util.ToastUtil
import root.electronclass.electronclass.databinding.ActivityMainBinding
import root.electronclass.electronclass.ext.CoroutineExceptionHandler
import root.electronclass.electronclass.grade.ClassFragment
import root.electronclass.electronclass.grade.model.PersonType
import root.electronclass.electronclass.home.HomeFragment
import root.electronclass.electronclass.mvp.GlobalParameter
import root.electronclass.electronclass.mvp.base.BaseResponse
import root.electronclass.electronclass.mvp.base.CallbackNext
import root.electronclass.electronclass.mvp.entity.CampusPoint
import root.electronclass.electronclass.mvp.entity.EcardInfo
import root.electronclass.electronclass.mvp.entity.VersionData
import root.electronclass.electronclass.mvp.rest.ClassApi
import root.electronclass.electronclass.mvp.rest.RestManager
import root.electronclass.electronclass.other.AttestationActivity
import root.electronclass.electronclass.other.FullImgActivity
import root.electronclass.electronclass.other.FullNoticeWebActivity
import root.electronclass.electronclass.other.NetworkChangeReceiver
import root.electronclass.electronclass.other.WebFragment
import root.electronclass.electronclass.other.dialog.AttendanceDialog
import root.electronclass.electronclass.other.dialog.SetDialog
import root.electronclass.electronclass.other.viewModel.MainViewModel
import root.electronclass.electronclass.personal.PersonalFragment
import root.electronclass.electronclass.personal.dialog.TipsDialog
import root.electronclass.electronclass.school.SchoolFragment
import java.io.File
import java.io.Serializable


class MainActivity : ViewBindingActivity<ActivityMainBinding>() {
    private val model: MainViewModel by viewModels()

    private val SET = 1000
    private val COUNTS = 4 // 点击次数
    private val DURATION: Long = 1000 // 规定有效时间
    private var isAction = false //判断屏幕是否未被点击
    private var mHits = LongArray(COUNTS)
    private var fragmentTabAdapter: FragmentTabAdapter? = null
    private var dialog: Dialog? = null
    private var startDialogTv: TextView? = null
    private var startDialogPro: TextView? = null
    private var networkChangeReceiver = NetworkChangeReceiver()
    private var inactivityJob: Job? = null

    private val fragments1: ArrayList<Fragment> = object : ArrayList<Fragment>() {
        init {
            add(ClassFragment()) //班级中心
            add(SchoolFragment()) //校园中心
            add(HomeFragment()) //主界面
            add(PersonalFragment()) //个人中心
            add(ApplicationFragment()) //应用中心
        }
    }

    override fun onStart() {
        super.onStart()
        isVisible = true
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
    }

    override fun init() {
        binding.top.setup(lifecycle, null, true)
        SPUtils.getInstance().put("runResult", false)
        val filter = IntentFilter()
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
        registerReceiver(networkChangeReceiver, filter)
        FaceSdk.get().init(this)
        initFragment()
        request_permissions()
        binding.top.schoolIcon.setOnClickListener {
            continuousClick(true)
        }

//        binding.face.setOnClickListener {
//            startActivity(Intent(this@MainActivity, EntryFaceActivity::class.java))
//        }
        binding.attendance.setOnClickListener {
            AttendanceDialog().also {
                it.arguments = bundleOf(
                    CommonDialogFragment.TITLE to "考勤打卡",
                    CommonDialogFragment.CLOSE to true,
                )
            }.show(supportFragmentManager, "Attendance")
        }
//        binding.scanIv.setOnClickListener {
//            binding.scanCl.isVisible = !binding.scanCl.isVisible
//        }
        initDialog()
        if (GlobalParameter.getEcardInfo().type == 5) {
            setKESystem()
//            binding.face.isVisible = false
        } else {
            setHKSystem()
        }
        downApk()
        campusPoint()
        runResult()
        startFullScreenImgTimer()
        cycleSetTime()
        UpgradeManager.getInstance()
            .checkUpgrade(false, null, DefaultUpgradeStrategyRequestCallback())
    }

    // 请求多个权限
    private fun request_permissions() {
        // 创建一个权限列表，把需要使用而没用授权的的权限存放在这里
        val permissionList: MutableList<String> = java.util.ArrayList()

        // 判断权限是否已经授予，没有就把该权限添加到列表中
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
            !== PackageManager.PERMISSION_GRANTED
        ) {
            permissionList.add(Manifest.permission.CAMERA)
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
            !== PackageManager.PERMISSION_GRANTED
        ) {
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
            !== PackageManager.PERMISSION_GRANTED
        ) {
            permissionList.add(Manifest.permission.READ_EXTERNAL_STORAGE)
        }

        // 如果列表为空，就是全部权限都获取了，不用再次获取了。不为空就去申请权限
        if (!permissionList.isEmpty()) {
            ActivityCompat.requestPermissions(
                this,
                permissionList.toTypedArray(), 1002
            )
        } else {
            Log.i("", "request_permissions: no need request.")
        }
    }


    private fun runResult() {
        lifecycle.coroutineScope.launch(CoroutineExceptionHandler()) {
            delay(10000)
            SPUtils.getInstance().put("runResult", true)
        }
    }

    private fun campusPoint() {
        RestManager.getInstance().initRest().campusPoint()
            .enqueue(object : CallbackNext<BaseResponse<List<CampusPoint>>>(mDialogViewModel) {
                override fun onSuccessful(
                    call: Call<BaseResponse<List<CampusPoint>>>?,
                    response: BaseResponse<List<CampusPoint>>,
                ) {
                    if (response.rows != null && response.rows.isNotEmpty() && response.rows[0].qrCodePicFormat != null && response.rows[0].qrCodePicFormat.size > 0) {
//                        binding.scanIv.visibility = View.VISIBLE
                        binding.scan.setImageURI(response.rows[0].qrCodePicFormat[0].url)
                    }

                }

                override fun onError(
                    call: Call<BaseResponse<List<CampusPoint>>>?,
                    response: BaseResponse<List<CampusPoint>>?,
                ) {
                }

            })
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onNetWorkEvent(event: NetWorkEvent) {
        Log.i("", "onNetWorkEvent: -------")
        if (!event.connect) {
            TipsDialog().also {
                it.arguments = bundleOf(
                    CommonDialogFragment.TITLE to "温馨提示",
                    TipsDialog.DATA to "当前设备网络异常，应用无法正常使用。请排查网络问题，网络恢复后，应用将恢复正常",
                    CommonDialogFragment.CLOSE to true
                )
            }.show(supportFragmentManager, "TIPS")
        }
    }

    private fun initDialog() {
        val view: View =
            (getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater).inflate(
                R.layout.download_dialog,
                null
            )
        dialog = Dialog(this@MainActivity, R.style.CustomDialog)
        dialog!!.addContentView(
            view,
            ActionBar.LayoutParams(
                ActionBar.LayoutParams.MATCH_PARENT,
                ActionBar.LayoutParams.WRAP_CONTENT
            )
        )
        startDialogTv = view.findViewById(R.id.start_tv)
        startDialogPro = view.findViewById(R.id.progress_tv)
    }

    private fun setHKSystem() { //设置默认 Launcher 设置 Launcher 后，效果即时生效，但是系统需要 10s+保存配置保证重启后 仍为设置的 Launcher 应用
        InfoSystemApi.setLauncherForced("root.electronclass.electronclass") //系统保护程序使能
        InfoUtilApi.addProtection(
            "root.electronclass.electronclass", "root.electronclass.electronclass", true,
            "root.electronclass.electronclass.currency.LauncherActivity", ""
        )
        InfoUtilApi.enableProtection("root.electronclass.electronclass", true) //设置定时开关机
        DeviceType.HK_OFF_ON()
        /**
         * 人脸SDK初始化，使用人脸功能前必须调用初始化。
         * 初始化需要放到MainActivity中，
         */
        FaceSdk.get().init(this)
    }

    private fun setKESystem() {
        DeviceType.KE_OFF_ON(this@MainActivity)
    }

    private val handler = Handler(Looper.getMainLooper())
    private val interval: Long = 2 * 60 * 60 * 1000 // 2 小时的毫秒数
    private val runnable = object : Runnable {
        override fun run() {
            // 在这里执行你的操作
            executeTask()

            // 继续下一次
            handler.postDelayed(this, interval)
        }
    }

    private fun cycleSetTime() {
        handler.postDelayed(runnable, interval)
    }

    private fun executeTask() {
        RestManager.getInstance().initRest().getElectorInfo(GlobalParameter.getDeviceCode())
            .enqueue(object : CallbackNext<BaseResponse<EcardInfo>>(mDialogViewModel) {

                override fun onSuccessful(call: Call<BaseResponse<EcardInfo>>,
                    response: BaseResponse<EcardInfo>,
                ) {
                    if (response.isSuccess) {
                        GlobalParameter.setEcardInfo(response.rows)
                        if (GlobalParameter.getEcardInfo().type == 5) {
                            setKESystem()
                        } else {
                            DeviceType.HK_OFF_ON()
                        }
                    }
                }

                override fun onError(
                    call: Call<BaseResponse<EcardInfo>>,
                    response: BaseResponse<EcardInfo>,
                ) {
                }

                override fun onFail(
                    call: Call<BaseResponse<EcardInfo>>?,
                    t: Throwable?,
                    response: Response<BaseResponse<EcardInfo>>?,
                ) {
                }

            })
    }


    /**
     * logo连点判断
     */
    private fun continuousClick(b: Boolean) { //每次点击时，数组向前移动一位
        System.arraycopy(mHits, 1, mHits, 0, mHits.size - 1) //为数组最后一位赋值
        mHits[mHits.size - 1] = SystemClock.uptimeMillis()
        if (mHits[0] >= SystemClock.uptimeMillis() - DURATION) {
            mHits = LongArray(COUNTS) //重新初始化数组
            if (b) {
                SetDialog().also {
                    it.arguments = bundleOf(
                        CommonDialogFragment.TITLE to "班牌登录",
                        CommonDialogFragment.CLOSE to true,
                        CommonDialogFragment.CANCEL to "取消",
                        CommonDialogFragment.OK to "确定"
                    )
                }.show(supportFragmentManager, "SET")
            }
        }
    }

    private var isVisible = true

    override fun onRestart() {
        super.onRestart()
        isVisible = true
        startFullScreenImgTimer()
    }

    override fun onResume() {
        super.onResume()
        isVisible = true
    }


    private fun startFullScreenImgTimer() {
        inactivityJob?.cancel()
        inactivityJob = lifecycleScope.launch(CoroutineExceptionHandler()) {
            while (isVisible) {
                delay(10 * 60 * 1000)
                if (!isDestroyed && !isFinishing && !isAction) {
                    val notice = RestManager.getInstance().initRest().fullScreenNotice()
                    if (notice.isSuccess && notice.rows != null && notice.rows.startTime != null && notice.rows.endTime != null) { //有全屏通知就进入全屏通知数据，没有就进入屏幕保护界面
                        val intent = Intent(this@MainActivity, FullNoticeWebActivity::class.java)
                        intent.putExtra(
                            "url",
                            WebFragment.SCHOOL_NOTIFICATION.format(notice.rows.noticeId)
                        )
                        intent.putExtra("endTime", notice.rows.endTime)
                        startActivity(intent)
                    } else {
                        val noticeImg = RestManager.getInstance().initRest()
                            .listByDepartId(GlobalParameter.getEcardInfo().classId)
                        if (noticeImg.isSuccess && noticeImg.rows.isNotEmpty()) {
                            val intent = Intent(this@MainActivity, FullImgActivity::class.java)
                            intent.putExtra("fullScreenImgData", noticeImg.rows as Serializable)
                            startActivity(intent)
                        }
                    }
                    isVisible = false
                    inactivityJob?.cancel()
                }
                isAction = false
            }

        }

    }


    private var portion = 2
    private fun initFragment() {

        fragmentTabAdapter =
            FragmentTabAdapter(this, fragments1, R.id.frameLayout, findViewById(R.id.radioGroup), 2)
        fragmentTabAdapter?.onRgsExtraCheckedChangedListener =
            object : OnRgsExtraCheckedChangedListener() {
                override fun OnRgsExtraCheckedChanged(
                    radioGroup: RadioGroup?, checkedId: Int, index: Int,
                ) {
                    when (index) {

                        0 -> {
                            portion = index
                            binding.top.title(GlobalParameter.getEcardInfo().className)
                        }

                        1 -> {
                            portion = index
                            binding.top.title("校园空间")
                        }

                        2 -> {
                            portion = index
                            binding.top.title(null, true)
                        }

                        3 -> {
                            binding.top.title("个人空间")
                            val intent = Intent(this@MainActivity, AttestationActivity::class.java)
                            startActivityForResult(intent, AttestationActivity.personal)
                        }

                        4 -> {
                            portion = index
                            binding.top.title("应用中心")
                        }
                    }
                }
            }
    }

    private fun downApk() {
        RestManager.getInstance().initRest().version()
            .enqueue(object : CallbackNext<BaseResponse<VersionData>>(mDialogViewModel) {
                override fun onSuccessful(
                    call: Call<BaseResponse<VersionData>>?,
                    response: BaseResponse<VersionData>,
                ) {
                    if (response.isSuccess && getVersionCode(this@MainActivity) < response.rows.version.toInt() &&
                        !response.rows.pkgUrl.isNullOrEmpty()) {
                        UpdateApp.getInstance().setAutoInatall(false) //是否弹起安装apk
                            .setUpdateListener(object : UpdateListener {
                                override fun start() {
                                    startDialogTv?.text = "开始下载"
                                    dialog?.show()
                                }

                                override fun progress(progress: Int) {
                                    if (dialog != null) {
                                        startDialogPro?.text = "进度：$progress"
                                    }
                                }

                                override fun downFinish() {
                                    if (dialog != null) {
                                        startDialogTv?.text = "下载完成"
                                        dialog?.dismiss()
                                        val path = Environment.getExternalStorageDirectory()
                                            .toString() + File.separator + "download/app.apk"
                                        Log.i("MainActivity", "downFinish: $path")
                                        if (GlobalParameter.getEcardInfo().type == 5) {
                                            UpdateApp.getInstance().startInstall(this@MainActivity)
                                        } else {
                                            InfoUtilApi.silentInstallation(path)
                                        }
                                    }
                                }

                                override fun downFail(throwable: Throwable) {
                                    ToastUtil.showToast(
                                        this@MainActivity,
                                        "下载失败：" + throwable.message
                                    )
                                    if (dialog != null) {
                                        dialog?.dismiss()
                                    }
                                }
                            }).downloadApp(
                                this@MainActivity,
                                response.rows.pkgUrl,
                                R.mipmap.ic_launcher,
                                R.mipmap.ic_launcher
                            )
                    }
                }

                override fun onError(
                    call: Call<BaseResponse<VersionData>>,
                    response: BaseResponse<VersionData>?,
                ) {
                    toast(response?.msg)
                }

            })
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        if (event.action == MotionEvent.ACTION_DOWN) { //点击过屏幕就设置成true
            isAction = true
        }
        return super.onTouchEvent(event)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == SET) {
                setWindowBackGround()
            } else if (requestCode == AttestationActivity.personal) {
                val result: Boolean = data?.getBooleanExtra("SUCCESS", false) as Boolean
                if (result) {
                    lifecycleScope.launch(CoroutineExceptionHandler { }) {
                        val result = withContext(Dispatchers.IO) { ClassApi.service.login() }
                        if (result != null && result.isSuccess) {
                            if (result.rows.personType == PersonType.TEACHER) {
                                TipsDialog().also {
                                    it.arguments = bundleOf(
                                        CommonDialogFragment.TITLE to "温馨提示",
                                        TipsDialog.DATA to "个人空间仅针对学生开发，教职工个人信息请通过手机查看",
                                        CommonDialogFragment.CLOSE to true
                                    )
                                }.show(supportFragmentManager, "PERSON")
                                findViewById<RadioButton>(binding.radioGroup.getChildAt(portion).id).isChecked =
                                    true
                            } else {
                                portion = 3
                                EventBus.getDefault().post(PersonSuccess())
                            }
                        }
                    }

                } else {
                    findViewById<RadioButton>(binding.radioGroup.getChildAt(portion).id).isChecked =
                        true
                }
            }
            if (requestCode == RESULT_CANCELED) {
                isAction = false
                startFullScreenImgTimer()
            }
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        /**
         * 应用退出时，需要释放人脸SDK模块内部资源，整个应用周期内不需要释放。
         * 如中途调用了释放，再次使用前需要先初始化。
         */
        kotlin.runCatching { FaceSdk.get().destroy() }
        EventBus.getDefault().unregister(this)
        unregisterReceiver(networkChangeReceiver);
        handler.removeCallbacks(runnable)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String?>,
        grantResults: IntArray,
    ) {
        super.onRequestPermissionsResult(requestCode, permissions!!, grantResults)
        when (requestCode) {
            1002 ->                 // 1002请求码对应的是申请多个权限
                if (grantResults.isNotEmpty()) {
                    // 因为是多个权限，所以需要一个循环获取每个权限的获取情况
                    var i = 0
                    while (i < grantResults.size) {

                        // PERMISSION_DENIED 这个值代表是没有授权，我们可以把被拒绝授权的权限显示出来
                        if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                            Log.i(
                                "",
                                "onRequestPermissionsResult: reject permission.exit"
                            )
                        }
                        i++
                    }
                }
        }
    }

    /**
     *
     *
     * @param page 跳转界面
     * @param bundle 参数
     */
    fun selectPage(page: Page, bundle: Bundle) {
        val index = fragments1.indexOfFirst { it::class.java == page.clazz }
        portion = index
        findViewById<RadioButton>(binding.radioGroup.getChildAt(index).id).isChecked = true
        fragments1.getOrNull(index)?.let {
            if (it is IPage) {
                it.onPageSelected(bundle)
            }
        }
    }

    enum class Page(val clazz: Class<*>) {
        SCHOOL(SchoolFragment::class.java), //校园中心
        CLASS(ClassFragment::class.java), //班级中心
        HOME(HomeFragment::class.java), //主界面
        PERSONAL(PersonalFragment::class.java), //个人中心
        APPLICATION(ApplicationFragment::class.java), //应用中心
    }

    interface IPage {

        /**
         * 界面选中
         */
        fun onPageSelected(bundle: Bundle?)
    }


}

